<template>
  <div>
    <div class="mainCon" v-loading="loading">
      <div class="containercontent">
        <div class="seachTip selectw100">
          <div class="inlineblock verticalmiddle infoitem">
            <div class="inlineblock verticalmiddle">
              起止日期
            </div>
            <div class="inlineblock verticalmiddle informationItem">
              <el-date-picker clearable v-model="qizhiriqi" size="mini" type="daterange" value-format='yyyy-MM-dd' range-separator="-"
                start-placeholder="开始日期" :picker-options="pickerOptions" end-placeholder="结束日期" @change="doSearch">
              </el-date-picker>
            </div>
          </div>
          <div class="inlineblock verticalmiddle infoitem">
            <div class="inlineblock verticalmiddle">
              登记单状态
            </div>
            <div class="inlineblock verticalmiddle informationItem">
              <el-select v-model="instockListParams.status" placeholder="请选择" clearable size="mini" filterable @change="doSearch">
                <el-option v-for="item in zhuangtai" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </div>
          </div>
          <div class="inlineblock basicRightDistanceA searchIcon">
            <el-button size="mini" @click="doSearch">搜索</el-button>
            <el-button size="mini" @click="emptySearch">清空</el-button>
          </div>
        </div>
        <div class="separaterowTable">
          <div class="tableTittle">
            <div><span class="fontImpact">1</span><span>入库登记</span></div>
            <el-button type="primary" size="mini" @click="dengji" style="float:right;margin-left:8px;" v-if="userOpernation.add.display">入库登记</el-button>
            <form id="fileForm1" style="display:inline-block">
              <input type="file" name="file" id="file1" @change="upload1">
            </form>
            <el-button type="primary" size="mini" @click="daoru" style="float:right;;margin-left:8px;">导入</el-button>
						<el-button type="primary" size="mini" @click="dlownloadattachment" style="float:right">下载模板</el-button>
          </div>
          <el-table :data="rukushenqingTable" style="width: 100%" size="mini" class="tableCon">
            <el-table-column label="序号" min-width="50px">
              <template slot-scope="scope">
               {{scope.$index+(readQuery.page - 1) * readQuery.pageCount + 1}}
              </template>
            </el-table-column>
            <el-table-column property="billNo" label="单号" min-width="120px">
            </el-table-column>
            <el-table-column property="storekeeper" label="登记人" min-width="80px" :formatter="foramtterAccount">
            </el-table-column>
            <el-table-column property="createTime" label="入库时间" show-overflow-tooltip min-width="145px">
              <template slot-scope="scope">
                {{scope.row.hasOwnProperty('createTime')?scope.row.createTime.split('.')[0]:'/'}}

              </template>
            </el-table-column>

            <el-table-column property="status" label="登记单状态" :formatter="formatter" min-width="80px">
            </el-table-column>
           <!-- <el-table-column property="remark" label="备注" show-overflow-tooltip min-width="100px">
            </el-table-column> -->
            <el-table-column label="操作" min-width="200px" >
              <template slot-scope="scope">
                <el-button v-if="scope.row.status==2 && userOpernation.update.display" type="text" size="mini" @click="rukutijiao(scope.row)">编辑</el-button>
                <el-button v-if="scope.row.status==341" type="text" size="mini" @click="rukushenpi(scope.row)">入库审批</el-button>
                <el-button v-if="userOpernation.select.display" type="text" size="mini" @click="chakanruku(scope.row)">详情</el-button>
                <el-button v-if="scope.row.status==2 && userOpernation.delete.display" type="text" size="mini" @click="deleteRow(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="block changepages">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="readQuery.page" :page-sizes="[20, 30, 40]"
              :page-size="readQuery.pageCount" layout="total, sizes, prev, pager, next, jumper" :total="rowNumber">
            </el-pagination>
          </div>
        </div>
      </div>
    </div>
    <div v-if="rukudengjiShow">
      <rukudengji :status="danjuzhuangtai" :shenpi="shenpi" :instockParams="instockParams"></rukudengji>
    </div>
  </div>
</template>

<script>
  import { mapState } from 'vuex'
  import rukudengji from './ruKuDengJi.vue'



  export default {
    data() {
      return {
				errorMessageName: "",
        loading: false,
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now();
          },
        },
        rukushenqingTable: [],
        pageinfo: [],
        readQuery: {
          page: 1,
          pageCount: 20,
        },
        rowNumber: 0,

        instockListParams: {
          startDate: '',
          endDate: '',
          status: '',
        },
        instockParams: {
          billdate: this.util.date(),//(入库日期)
          storekeeper: JSON.parse(sessionStorage.getItem('laboratoryAccountInfo')).name,//(库管员)
          remark: "",//(备注)
          submitType: "",//(0:保存   1:提交)
          billNo: '',
          instockdetBeanList: []
        },
        //   materialList:[],
        userTableDate: [],
        enableStatusValue: '',
        searchName: '',
        currentPage: 1,
        materialTypeValue: '',
        chujudengjiShow: false,
        rukudengjiShow: false,
        zhuangtaiValue: '',
        zhuangtai: [
          {
            value: 2,
            label: '草稿'
          },
          {
            value: 341,
            label: '待审批'
          },
          {
            value: 342,
            label: '已登记'
          }
        ],
        qizhiriqi: '',
        danjuzhuangtai: '',
        shenpi: false,
      }
    },
    computed: {
      tabDivHeight() {
        return (window.innerHeight - 220)
      },
      ...mapState(['enableStatus', 'tableHeightA', 'typeofAbilityTableDate', 'materialType','EmployeeByLabs']),
    },
    components: {
      rukudengji
    },
    mounted() {
      //  this.readEnMaterialList()
      //  this.readEnableMaterTypeList()
      this.readInstockList()
    },
    watch: {
      readQuery: {
        handler(val, oldVal) {
          this.readInstockList(this.readQuery)
        },
        deep: true
      }

    },
    props: ['userOpernation'],
    methods: {

      //处理状态
      formatter(row, column, cellValue, index) {
        return this.util.changeStatus({ cellValue: cellValue, list: this.zhuangtai })
      },
      foramtterAccount(row, column, cellValue, index) {
        console.log(this.EmployeeByLabs)
        var res = null;
        for (var i in this.EmployeeByLabs) {
          if (cellValue == this.EmployeeByLabs[i].account) {
            res = this.EmployeeByLabs[i].name;
          }
        }
        return res ? res : cellValue;
      },
      deleteRow(row) {
        this.$confirm('是否删除此条信息？')
          .then(_ => {
            this.$http({
              apiUrl: 'resource/deleteInstock.htm',
              method: 'post',
              params: { id: row.id },
              isJson: false
            }).then(res => {
              if (res.code === 0) {
                console.log(res)
                this.$message({
                  showClose: true,
                  message: '删除成功！',
                  type: 'success'
                })
                this.readInstockList()
              }
            }).catch(err => {
              console.log(err)
            })
          })
      },
      //	4、(1)交互名称：获取入库详情
      // (2)url:readInstock.htm
      readInstock(id) {
        return new Promise((resolve, reject) => {
          this.$http({
            apiUrl: 'resource/readInstock.htm',
            method: 'post',
            params: { id: id },
            isJson: false
          }).then(res => {
            if (res.code === 0) {
              resolve(res)
            }
          }).catch(err => {
            console.log(err)
          })
        })

      },

      //	(1)交互名称：获取入库列表
      // (2)url:readInstockList.htm
      // (3)参数：startDate  开始时间(可选)
      //			endDate  结束时间(可选)
      //			status  登记状态(可选)

      readInstockList() {

        if (!!this.qizhiriqi) {
          this.instockListParams.startDate = this.qizhiriqi[0]
          this.instockListParams.endDate = this.qizhiriqi[1]
        } else {
          this.instockListParams.startDate = ''
          this.instockListParams.endDate = ''
        }
        this.instockListParams.page = this.readQuery.page;
        this.instockListParams.pageCount = this.readQuery.pageCount;
        this.$http({
          apiUrl: 'resource/readInstockList.htm',
          method: 'post',
          params: this.instockListParams,
        }).then(res => {
          if (res.code === 0) {
            this.rukushenqingTable = res.data
            this.pageinfo = res.pageinfo
            if (!res.pageinfo) {
              this.rowNumber = 0;
            } else if (res.pageinfo && !res.pageinfo.rowNumber) {
              this.rowNumber = 0;
            } else {
              this.rowNumber = res.pageinfo.rowNumber;
            }
          }
        })
      },
      emptySearch() {
        this.instockListParams.status = "";
        this.qizhiriqi = [];
        this.doSearch();
      },
      doSearch() {
        this.readQuery.page = 1;
        this.readInstockList()
      },
      handleSizeChange(val) {
        this.readQuery.pageCount = val;
      },
      handleCurrentChange(val) {
        this.readQuery.page = val;
      },
      editUser: function (row) {

      },
      changeUserStatus: function (row) {
        console.log(row);
      },

      rukushenpi(row) {
        this.rukudengjiShow = false;
        this.readInstock(row.id).then(res => {
          this.instockParams = res.data
          this.rukudengjiShow = true;
          this.danjuzhuangtai = 'rukushenpi';
          this.shenpi = true;
        })
      },
      chakanruku(row) {
        this.readInstock(row.id).then(res => {
         
          this.instockParams = res.data
          this.rukudengjiShow = true;
          this.danjuzhuangtai = 'chakanruku';
          this.shenpi = true;
        })
      },
      daoru() {
        document.getElementById("file1").click()
      },
      // 导入文件
      upload1(event) {
        this.loading = true;
        var files = document.getElementById('file1').files[0];
        if (files == undefined) {
          this.loading = false;
          return;
        }
        var formData = new FormData();
        formData.append('file', files)
        this.$axios({
          method: 'post',
          url: '/resource/importInstockByExcel.htm',
          data: formData,
          headers: {
            'Content-Type': 'multipart/form-data',
            'token':sessionStorage.getItem('loginAccount')?sessionStorage.getItem('loginAccount'):undefined
          }
        }).then(res => {
          this.loading = false;
          event.target.value= "";
          if (res.data.code == 0) {
            this.$notify({
              title: '消息',
              message: res.data.description,
              type: 'success'
            })
            this.readInstockList();

          } else {
					this.errorMessageName = res.data.description;
					this.$confirm("文件导入出错，是否下载错误信息?", "提示", {
						confirmButtonText: "下载",
						cancelButtonText: "取消",
						type: "warning",
						})
						.then(() => {
							//下载
							this.downloadErrorMessage();
						})
						.catch((e) => {
							//取消
						});
          }
        })
      },
      downloadErrorMessage() {
        let token = sessionStorage.getItem('loginAccount')?sessionStorage.getItem('loginAccount'):undefined
				window.open(process.env.baseUrl + 'AnnexAction/errorExport.htm?filename=' + this.errorMessageName);
			},
      // 下载附件
			dlownloadattachment(row) {
				var url = "/resource/getInstockByExcel.htm"
        let token = sessionStorage.getItem('loginAccount')?sessionStorage.getItem('loginAccount'):undefined
				window.open(process.env.baseUrl + url + '?id=' + row.id + "&token=" + token);
			},
      dengji() {
        this.instockParams = {
          billdate: this.util.date(),//(入库日期)
          storekeeper: JSON.parse(sessionStorage.getItem('laboratoryAccountInfo')).name,//(库管员)
          remark: "",//(备注)
          submitType: "",//(0:保存   1:提交)
          billNo: '',
          supplier: '',
          instockdetBeanList: []
        },
          this.rukudengjiShow = true;
        this.danjuzhuangtai = 'rukudengji';
        this.shenpi = false;
      },
      rukutijiao(row) {
        this.rukudengjiShow = false;
        this.readInstock(row.id).then(res => {
           console.log(res.data.instockdetBeanList)
          if(res.data.instockdetBeanList != undefined){
            for(var i in res.data.instockdetBeanList){
              var numberBatch = res.data.instockdetBeanList[i].number + res.data.instockdetBeanList[i].batch
              this.$set(res.data.instockdetBeanList[i],'numberBatch',numberBatch)
            }
          }
          this.instockParams = res.data
          this.rukudengjiShow = true;
          this.danjuzhuangtai = 'rukutijiao';
          this.shenpi = false;

        })
      }
    }
  }

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .containercontent .width73 {
    width: 73px;
  }
  #fileForm1,
  #file1 {
    width: 50px;
    height: 20px;
    opacity: 0;
    position: absolute;
    left: 0;
    top: 0;
    z-index: -1;
  }
</style>